from django.core.serializers import serialize
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from cate.models import Cate
from cate.serializers import CateSerializer


# Create your views here.
class DelView(APIView):
    def delete(self, request):
        cate = Cate.objects.filter(id=request.GET.get("id")).first()
        if cate:
            cate.delete()
            return Response({'code':0, 'msg':"删除文章分类成功！", 'data':None})
        return Response({'code': 1, 'msg': "删除文章分类失败", 'data': request.GET.get("id")})


class InfoView(APIView):
    # 获取
    def get(self, request):
        cate = Cate.objects.filter(id=request.GET.get("id")).first()
        serializer = CateSerializer(cate)

        return Response({'code':0, 'msg':'获取文章分类成功！', 'data':serializer.data})

    # 更新
    def put(self, request):
        cate = Cate.objects.filter(id=request.data.get('id')).first()
        serializer = CateSerializer(cate, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response({'code':0, 'msg':"更新分类信息成功！", 'data':None})
        return Response({'code':2, 'msg':"更新分类信息失败！", 'data':request.data.get('id')})

class AddView(APIView):
    # 增加
    def post(self, request):
        serializer = CateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'code': 0, 'msg': "新增文章分类成功！", 'data': None})
        return Response({'code': 1, 'msg': '此分类已存在！', 'data': request.data})

class ListView(APIView):
    # 获取
    def get(self, request):
        cate = Cate.objects.all()
        # 序列化
        serializer = CateSerializer(cate, many=True)
        return Response({'code':0, 'msg':'获取文章分类列表成功！', 'data':serializer.data})